from fastapi import FastAPI
from routers import *
from dependencies import create_db_and_tables, engine, drop_db_and_tables
from contextlib import asynccontextmanager
import logging
from fastapi.middleware.cors import CORSMiddleware

logging.basicConfig(level=logging.INFO)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # # 删除所有表
    # drop_db_and_tables()
    # 在应用启动时创建数据库和表
    create_db_and_tables()
    logging.info("应用启动：创建数据库和表")
    yield
    # 在应用关闭时关闭数据库连接
    engine.dispose()
    logging.info("应用关闭：关闭数据库连接")


# 初始化定义App
app = FastAPI(
    title="应用名称",  # 应用名称
    summary="应用简介",  # 应用简介
    description="应用描述",  # 应用描述
    version="0.1.0",  # 版本号
    lifespan=lifespan,
)


# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 导入子模块
app.include_router(auth.router)
app.include_router(register_users.router)
app.include_router(scale.router)
app.include_router(scaledetail.router)
app.include_router(user.router)
app.include_router(org.router)
app.include_router(role.router)
app.include_router(menu.router)
app.include_router(dic.router)


@app.get("/")
def index():
    return '成功'
    


# if __name__ == "__main__":
#     import uvicorn
#     uvicorn.run(app, host="127.0.0.1", port=8000)
